﻿using System;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;

namespace Twilight.Controls
{
    /// <summary>
    /// Based on logic from the LinkLabel project to turn text into a collection of TextBlocks
    /// and Hyperlinks so that the WrapPanel can display then as a single TextBlock.
    /// http://www.codeplex.com/SilverlightLinkLabel
    /// </summary>
    public class TweetBlock : TextWrapPanel
    {
        public TweetBlock()
        {
            linkRegex = new Regex(@"((?<uri>(ht|f)tp(s?)\://[A-Za-z0-9_./\?&=\-]+)|(?<user>\@\w+))", RegexOptions.Singleline | RegexOptions.ExplicitCapture);
        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(TweetBlock), new PropertyMetadata(TextChanged));

        public static void TextChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((TweetBlock)o).OnTextChanged((string)e.NewValue);
        }

        protected override void ProcessLinkMatch(Match match)
        {
            if (match.Groups["uri"].Success)
            {
                var uri = match.Groups["uri"].Value;
                Children.Add(new HyperlinkButton()
                {
                    Content = uri,
                    NavigateUri = new Uri(uri),
                    Style = LinkStyle
                });
            }
            else
            {
                var user = match.Groups["user"].Value;
                Children.Add(new HyperlinkButton()
                {
                    Content = user,
                    NavigateUri = new Uri(string.Format("http://twitter.com/{0}", user.Substring(1))),
                    Style = LinkStyle
                });
            }
        }
    }
}
